package com.blog.config;


import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;


@Configuration
public class ThreadPoolConfig {
    @Bean(name = "articleSyncExecutor")
    public ExecutorService articleSyncExecutor() {
        // 核心线程数，根据cpu核心数调整
        int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;

        // 最大线程数,限制资源消耗
        int maxPoolSize = 20;

        //队列容量
        int queueCapacity = 100;

        //空闲线程存活时间
        long keepAliveTime = 60L;

        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("article-sync-pool-%d")
                .build();
        // 拒绝策略
        RejectedExecutionHandler rejectionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(queueCapacity),
                threadFactory,
                rejectionHandler

        );
    }
}
